<template>
  <div class="home-view">
    <!-- 搜索区域 -->
    <div class="search-section">
      <SearchFilters @search="handleSearch" />
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-checkbox-group v-model="selectedFilters" @change="fetchHotels">
        <el-checkbox value="freeCancellation">免费取消</el-checkbox>
        <el-checkbox value="breakfastIncluded">含早餐</el-checkbox>
        <el-checkbox value="swimmingPool">游泳池</el-checkbox>
      </el-checkbox-group>

      <el-select v-model="sortBy" placeholder="排序方式" @change="fetchHotels">
        <el-option label="价格从低到高" value="price_asc" />
        <el-option label="价格从高到低" value="price_desc" />
        <el-option label="评分从高到低" value="rating_desc" />
      </el-select>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 酒店列表 -->
    <div v-else class="hotel-list">
      <template v-if="filteredHotels.length > 0">
        <HotelCard v-for="hotel in paginatedHotels" :key="hotel.id" :hotel="hotel" @click="viewHotelDetail(hotel.id)" />
      </template>
      <div v-else class="no-data">
        <el-empty description="没有找到符合条件的酒店" />
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="filteredHotels.length"
        :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper"
        @current-change="handlePageChange" @size-change="handleSizeChange" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import SearchFilters from '../components/SearchFilters.vue'
import HotelCard from '../components/HotelCard.vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 搜索参数
const searchParams = ref({
  city: '',
  checkIn: new Date(),
  checkOut: new Date(Date.now() + 24 * 60 * 60 * 1000),
  children: 0,
  adults: 1
})

// 筛选和排序
const selectedFilters = ref([])
const sortBy = ref('price_asc')
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)

// 酒店数据
const hotels = ref([])

// 处理搜索
const handleSearch = (params) => {
  searchParams.value = params
  currentPage.value = 1
  fetchHotels()
}

// 获取酒店数据
const fetchHotels = async (isSearch = false) => {
  loading.value = true;
  try {
    // 1. 先查询所有符合条件的酒店
    const hotelsResponse = await axios.get('http://localhost:8080/hotels/search', {
      params: {
        keyword: searchParams.value.city,
        page: currentPage.value,
        size: pageSize.value,
      },
    });

    const hotelsList = hotelsResponse.data.records || [];
    
    // 2. 遍历每个酒店，查询其房型信息，并筛选出符合条件的酒店
    const validHotels = [];
    
    for (const hotel of hotelsList) {
      try {
        const roomTypesResponse = await axios.get(`http://localhost:8080/room-types/hotel/${hotel.id}`, {
          params: {
            id:hotel.id,
            children: searchParams.value.children,
            adult: searchParams.value.adults,
          },
        });

        const roomTypes = roomTypesResponse.data || [];
        // 检查该酒店是否有至少一个房型能容纳 `adult + children`
        const hasValidRoomType = roomTypes.some(
          (room) => room.maxOccupancy >= searchParams.value.adults + searchParams.value.children
        );

        // 如果该酒店有符合条件的房型，则保留
        if (hasValidRoomType) {
          validHotels.push(hotel);
        }
      } catch (error) {
        console.error(`查询酒店 ${hotel.id} 的房型失败:`, error);
      }
    }

    // 3. 更新最终可显示的酒店列表
    hotels.value = validHotels;
    console.log('最终显示的酒店列表:', hotels.value);
  } catch (error) {
    ElMessage.error('获取数据失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

// 过滤酒店
const filteredHotels = computed(() => {
  let result = [...hotels.value]

  // 应用筛选
  if (selectedFilters.value.includes('freeCancellation')) {
    result = result.filter(h => h.freeCancellation)
  }
  if (selectedFilters.value.includes('breakfastIncluded')) {
    result = result.filter(h => h.breakfastIncluded)
  }
  if (selectedFilters.value.includes('swimmingPool')) {
    result = result.filter(h => h.swimmingPool)
  }

  // 应用排序
  if (sortBy.value === 'price_asc') {
    result.sort((a, b) => a.price - b.price)
  } else if (sortBy.value === 'price_desc') {
    result.sort((a, b) => b.price - a.price)
  } else if (sortBy.value === 'rating_desc') {
    result.sort((a, b) => (b.rating || 0) - (a.rating || 0))
  }

  return result
})

// 分页数据
const paginatedHotels = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredHotels.value.slice(start, end)
})

// 分页变化处理
const handlePageChange = (newPage) => {
  currentPage.value = newPage
}

const filteredHotel = computed(() => {
  if (!hasSearched.value) return []
  const { adult } = searchForm.value
  const { children } = searchForm.value

  if (!adult) return []

  return hotel.value.roomTypes.filter(room => {
    // 筛选条件：房间最大入住人数 >= 选择的人数
    return room.maxOccupancy >= adult + children
  })
})
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
}

// 查看酒店详情
const viewHotelDetail = (hotelId) => {
  router.push(`/hotel/${hotelId}`)
}

// 初始加载数据
onMounted(() => {
  fetchHotels()
})

// 监听筛选条件变化
watch([selectedFilters, sortBy], () => {
  currentPage.value = 1
})
</script>

<style scoped>
.home-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.search-section {
  background: #003b95;
  padding: 20px;
  border-radius: 5px;
  margin-bottom: 20px;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f5f5;
  border-radius: 5px;
}

.hotel-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.loading {
  padding: 50px 0;
  text-align: center;
}

.no-data {
  grid-column: 1 / -1;
  text-align: center;
  padding: 50px 0;
}
</style>